package com.linkage.jz.bankruptcy.activity.Project;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingReadMeActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.MyProInfo;
import com.linkage.jz.bankruptcy.fragment.Project.ProManagerListFrgment;
import com.linkage.jz.bankruptcy.fragment.Project.ProSelManagerListFrgment;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.CreateGroupDialog;
import com.linkage.jz.bankruptcy.widget.PopupMenu;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * A login screen that offers login via email/password.
 */
public class SelManagerListActivity extends BaseActivity {
    private static final String TAG = PersonSettingReadMeActivity.class.getSimpleName();
    private ShapeLoadingDialog shapeLoadingDialog;
    private CreateGroupDialog createGroupDialog;
    private static MyProInfo mInfo;
    private PopupMenu popupMenu;
    ProSelManagerListFrgment groupChildrenCollect;

    private View menuAction;

    private static String isOpen;
    public static void start(Context context, MyProInfo info,String open) {
        mInfo = info;
        isOpen = open;
        Intent intent = new Intent(context, SelManagerListActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pro_managelist);
        initview();
        shapeLoadingDialog = new ShapeLoadingDialog(this);

        init();
        popupMenu = new PopupMenu(this);
//        findViewById(R.id.icon_back).setVisibility(View.GONE);
    }

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {

    }

    @Override
    public void initTitle() {

    }

    @Override
    public void initView() {

    }

    public void setTitleNum(String str) {
        setTitle(str);
    }

    //初始化视图
    private void initview() {

//        menuAction = addMenu(new MenuAction(new OnClickListener(){
//
//            @Override
//            public void onClick(View v) {
//                popupMenu.showLocation(v);// 设置弹出菜单弹出的位置
//                // 设置回调监听，获取点击事件
//                popupMenu.setOnItemClickListener(new PopupMenu.OnItemClickListener() {
//                    @Override
//                    public void onClick(PopupMenu.MENUITEM item, String str) {
//                        createGroupDialog = new CreateGroupDialog(
//                                SelManagerListActivity.this,onClickListener);
//                        createGroupDialog.show();
//                    }
//                });
//            }
//        }, "", R.drawable.more_black));
    }

    private OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.btn_chancel_g:
                    createGroupDialog.dismiss();
                    break;
                case R.id.btn_save_g:
                    String name = createGroupDialog.text_name_g.getText().toString().trim();
                    addGroup(name);
                    break;

            }
        }
    };

    private void init() {
        groupChildrenCollect = new ProSelManagerListFrgment();
        groupChildrenCollect.setMenuAction(menuAction);
//        DocTmpGFrgment groupChildrenHasBuy = new DocTmpGFrgment();
        Bundle bundle = new Bundle();
        bundle.putString("proid", mInfo.getId());//这里的values就是我们要传的值
        bundle.putString("isOpen", isOpen);

        groupChildrenCollect.setArguments(bundle);
        getSupportFragmentManager().beginTransaction().replace(R.id.content, groupChildrenCollect).commitAllowingStateLoss();
    }

    public void addGroup(String groupname) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId", "");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)


                .add("projectId", mInfo.getId())
                .add("groupName", groupname)
                .build();

        String url = Consts.WEBURL_ADDGROUP;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        //更新UI
                        showToast("添加失败");
                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                showToast("添加成功", ToastUtil.TOAST_TYPE.SUCCESS);
                                createGroupDialog.dismiss();
                                groupChildrenCollect.getData();
                            }

                        });
//                        finish();

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                try {
                                    showToast("添加失败\n" + object.getString("msg"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    showToast("添加失败");
                                }
                            }
                        });

                    }
                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            showToast("添加失败");
                        }

                    });
                }
            }
        });
    }

}


